package com.ys.peony.app;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.interfaces.OnDownloadListener;
import com.ys.peony.utils.ToastUtils;

import java.io.File;
import java.util.Stack;

/**
 * 应用管理器类
 */
public class AppManager {
    public final static String path = BaseApplication.getInstance().getFilesDir().getAbsolutePath() + "/apk" + "/ys.apk";
    private static Stack<Activity> activityStack;
    private static AppManager instance;
    private ProgressDialog progressDialog;

    private AppManager() {
    }

    /**
     * 单一实例
     */
    public static AppManager getAppManager() {
        synchronized (AppManager.class) {
            if (instance == null) {
                synchronized (AppManager.class) {
                    instance = new AppManager();
                }
            }
            return instance;
        }
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack.lastElement();
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack.lastElement();
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                Activity activity = activityStack.get(i);
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * 获取activity实体类
     */
    public Activity getActivityByName(String activityName) {
        Activity mact = null;
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                Activity activity = activityStack.get(i);
                if (activityName.equals(activity.getClass().getSimpleName())) {
                    mact = activity;
                }
            }
        }

        return mact;
    }

    /**
     * 移除activity
     */
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }
    }

    /**
     * @return
     * @Description 安装apk
     */
    public void installApk() {
        File file = new File(path);
        if (file == null) {
            return;
        }
        Context context = BaseApplication.getInstance();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = FileProvider.getUriForFile(context, "com.ys.yuansheng.fileprovider", file);  //包名.fileprovider
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 下载最新apk文件
     *
     * @param context
     */
    public void downloadApk(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载最新app");
        progressDialog.setMessage("请稍后...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();
        progressDialog.setCancelable(false);
        JCHttpManagerUtils jcHttpManagerUtils = new JCHttpManagerUtils();
        /*jcHttpManagerUtils.downLoadFile("http://116.62.140.218:8080/atom-business/download/app.apk", path, new OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    installApk();
                }
            }

            @Override
            public void onDownloading(int progress) {
                progressDialog.setProgress(progress);
            }

            @Override
            public void onDownloadFailed(Exception e) {
                ToastUtils.showToast("网络异常");
            }
        });*/
    }

    /**
     * 判断是否是最新的apk文件
     *
     * @return
     */
    public boolean isNewestApk(Context context) {
        boolean b = false;
        if (!b) {
            downloadApk(context);
        }
        return b;
    }
}
